package com.mhl.campuscabinet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.SoldProduct;
import com.mhl.entity.Tag;
import com.mhl.entity.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SettingActivity extends AppCompatActivity implements View.OnClickListener {

    // 存储所有商品标签
    private String[] labels = {"1", "2", "3", "4", "5", "6", "7", "8"};

    //本地数据
    private List<Tag> TagList = LocalData.getInstance().TagList;

    private List<Tag> LikedList = new ArrayList<>();
    //private List<String> labelList = new ArrayList<>();
    // 存储所有CheckBox
    private List<CheckBox> checkBoxList = new ArrayList<>();
    // 存储所有感兴趣的商品标签
    //private List<String> likedList = new ArrayList<>();
    //用来操作的
    private List<Integer> likedIntList = new ArrayList<>();
    // 网格布局
    private GridLayout gridLayout;
    // 昵称
    private EditText nickName;
    // 个人介绍
    private EditText description;
    // 保存修改
    private TextView save;
    // 退出登录
    private TextView exit;
    // 渲染和加载信息同步
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        gridLayout = (GridLayout) findViewById(R.id.grid_layout);

        // handler准备处理UI
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                loadLabels();
            }
        };
        //因为我先写的loadinfo
        //所以我把loadinfo提到前面这样不用请求两次
        loadInfo();
        save = (TextView) findViewById(R.id.save);
        exit = (TextView) findViewById(R.id.exit);
        save.setOnClickListener(this);
        exit.setOnClickListener(this);
        nickName = (EditText) findViewById(R.id.nick_name);
        description = (EditText) findViewById(R.id.describe);
    }

    // 加载所有标签，并根据其是否是本用户喜欢的标签初始化checkBox
    private void loadLabels() {
        System.out.println("Start load label");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.weight = 1.0f;
                // labels字符串数组仅供测试使用，请客户端改为labelList
                // 如何实现加载该用户已经选择的like tag？
                // 答案是根据遍历到的label是否exist in likedList(上面要求加载过了)，是的话
                // 请调用该语句：checkBox.setChecked(true);
                for (int i = 0; i < TagList.size(); i++) {
                    //labelList.add(labels[i]);
                    CheckBox checkBox = (CheckBox) getLayoutInflater().inflate(R.layout.activity_setting, null)
                            .findViewById(R.id.default_check_box);
                    checkBoxList.add(checkBox);
                    if (checkBox.getParent() != null) {
                        ((ViewGroup) checkBox.getParent()).removeView(checkBox);
                    }
                    checkBox.setText(TagList.get(i).getName());
                    gridLayout.addView(checkBox);


                }
                // 删除第一个默认的checkBox，它只是一个被抄袭样式的工具人
                CheckBox default_check_box = (CheckBox) findViewById(R.id.default_check_box);
                ((ViewGroup) default_check_box.getParent()).removeView(default_check_box);

                System.out.println("准备打钩！！！！！！！！！！！！！！！！");
                // 把喜欢的tag对应的单选框打勾
                for (int i = 0; i < LikedList.size(); i++) {
                    for (int j = 0; j < checkBoxList.size(); j++) {
                        if (checkBoxList.get(j).getText().toString().equals(LikedList.get(i).getName())) {
                            checkBoxList.get(j).setChecked(true);
                            System.out.println("No. " + i + " is true");
                        }
                    }
                }

                System.out.println("end load label");
            }
        });
    }

    // 加载个人信息
    private void loadInfo() {
//        nickName.setText("Rabbit");
//        description.setText("I am a terrible rabbit");
        System.out.println("Star load info");

        JSONObject userJson = new JSONObject();

        try {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            userJson.put("username", User.getInstance().getUsername());
            userJson.put("password", User.getInstance().getUserPassword());
            String json = userJson.toString();
            RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

            OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "login", requestBody, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    System.out.println(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String userString = response.body().string();
                    try {
                        int state = 1;
                        try {
                            JSONObject errcodeJson = new JSONObject(userString);
                            state = errcodeJson.getInt("errcode");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (state != 0) {
                            Toast.makeText(SettingActivity.this, "Can't load setting page", Toast.LENGTH_SHORT).show();
                        } else {
                            System.out.println("Setting info of user");
                            JSONObject userJson = new JSONObject(userString);
                            JSONObject userInfoJson = userJson.getJSONObject("data");
                            //nickName.setText(userInfoJson.getString("username"));
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    nickName.setText(User.getInstance().getUsername());
                                    try {
                                        description.setText(userInfoJson.getString("description"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                            JSONArray userlike = userInfoJson.getJSONArray("user_like");

                            System.out.println("likedlist!!!!!!!!!!!!!!!!");
                            System.out.println("likedList里有：");
                            //从本地数据找对like tag id 对应的名字 放入 LikedList
                            for (int i = 0; i < userlike.length(); i++) {
                                for (int j = 0; j < TagList.size(); j++) {
                                    if (TagList.get(j).getTag_id() == userlike.getInt(i)) {
                                        LikedList.add(TagList.get(j));
                                        System.out.println(LikedList.get(i).getName());
                                        break;
                                    }
                                }
                            }
                            // 通知handler更新UI
                            handler.sendEmptyMessage(1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

        //还有性别
        //nickName.setText("Rabbit");
        //description.setText(User.getUserDescription());
        System.out.println("end load info");
    }

    // 按钮监听
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save: {
                // 测试语句，点击保存，打印出选择的分类名称
                //System.out.println(Arrays.toString(likedList.toArray()));

                //在发送保存请求前
                //重新生成user like 的integer list
                likedIntList.clear();
                for (int i = 0; i < checkBoxList.size(); i++) {
                    if (checkBoxList.get(i).isChecked()) {
                        String name = checkBoxList.get(i).getText().toString();
                        for (int j = 0; j < TagList.size(); j++) {
                            if (TagList.get(j).getName().equals(name)) {
                                likedIntList.add(TagList.get(j).getTag_id());
                                break;
                            }
                        }
                    }
                }
                JSONObject jsonParam = new JSONObject();
                JSONObject userInfoJSON = new JSONObject();
                try {
                    //后端没有nickname 得加
                    //userInfoJSON.put("nickName",nickName.getText().toString());
                    //界面加个checkbox啥的选男女 才实现性别
                    //userInfoJSON.put("gender",gender);
                    jsonParam.put("description", description.getText().toString());
                    JSONArray likeList = new JSONArray();
                    for (int i = 0; i < likedIntList.size(); i++) {
                        likeList.put(likedIntList.get(i));
                    }
                    jsonParam.put("tag_list", likeList);

                    jsonParam.put("id", User.getUserId());


                    String json = jsonParam.toString();
                    MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                    RequestBody requestBody = RequestBody.Companion.create(json, mediaType);


                    OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "user/update", requestBody, new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            System.out.println(e);
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                            final String data = response.body().string();
                            int state = 1;

                            try {
                                JSONObject stateJson = new JSONObject(data);
                                state = stateJson.getInt("errcode");

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            Looper.prepare();

                            if (state == 2) {
                                Toast.makeText(SettingActivity.this, "Save failed", Toast.LENGTH_SHORT).show();
                                //重新加载界面
                            } else if (state == 1) {
                                Toast.makeText(SettingActivity.this, "Missing data", Toast.LENGTH_SHORT).show();
                                //重新加载界面
                            } else {
                                Toast.makeText(SettingActivity.this, "Upload succeeded", Toast.LENGTH_SHORT).show();
                                //重新加载界面
                                //刷新本地user实例
                                try {
                                    JSONObject userJson = new JSONObject(data);

                                    JSONObject userInfo = userJson.getJSONObject("data");
                                    JSONArray userLike = userInfo.getJSONArray("tag_list");
                                    //后端要加
                                    //User.setUserNickname(userInfo.getString("nickname"));
                                    //User.setUserGender(userInfo.getInt("gender"));
                                    User.setUserDescription(userInfo.getString("description"));
                                    //后端要加
                                    User.getUserLike().clear();
                                    for (int i = 0; i < userLike.length(); i++) {
                                        User.getUserLike().add(userLike.getInt(i));
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            Looper.loop();
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
            break;
            case R.id.exit: {

                Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
                //User.resetUser();
                LocalData.getInstance().TagList.clear();
                startActivity(intent);
            }
            break;
            default:
                break;
        }
    }
}